function encryptedWithIv(str,iv){
    var e=CryptoJS.enc.Utf8.parse(gete());
    var i=CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(str,e,{
        iv:i,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

function gete(){
    return "UB64crH558RAQcO33kIMtvSnqNq46gUs";
}

const coin="3a310d0842ed4dd1";

var vcCodeType = $("#VC_CODE_TYPE").val();
var vcCode = $("#VC_CODE").val();
var pwdStrength = $("#pwdStrength").val();
initVcCode();
if (window.location.href != window.top.location.href) {
    window.top.location.href = loginPage;
}
layui.config({
    base: getContextPath() + '/static/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'user'], function(){
    var $ = layui.$,form = layui.form;
    layer = layui.layer;
    form.render();
    //提交
    form.on('submit(LAY-user-login-submit)', formOn);
    initCommLogin();
});
var captchaFlg = false;
if(vcCode && vcCodeType == 3){
    $('#captchaContent').slideVerify({
        baseUrl:getContextPath(),  //服务器请求地址
        containerId:'loginBut',//pop模式 必填 被点击之后出现行为验证码的元素id
        mode:'pop', //展示模式:弹出
        beforeCheck:function(){
            let userName= $('#LAY-user-login-username').val();
            let password= $('#LAY-user-login-password').val();
            if(!userName){
                $("#errorMsg").html("请输入用户名");
                return false;
            }
            if(!password){
                $("#errorMsg").html("请输入密码");
                return false;
            }
            return true
        },
        ready : function() {},  //加载完毕的回调
        success : function(params) { //成功的回调
            captchaFlg = true;
            $("#captchaVer").val(params.captchaVerification);
            formOn();
        },
        error : function() {}
    });
}

// 是否验证通过标识
var pointFlag = false;
var nc_token,NC_Opt,nc;
var layer;

function initVcCode(){
    if(vcCode&& vcCodeType == 2){
        /*
         *  滑动验证
         */
        nc_token = ["CF_APP_1", (new Date()).getTime(), Math.random()].join(':');
        NC_Opt = {
            renderTo: "#point-yz-id",
            appkey: "CF_APP_1",
            scene: "register",
            token: nc_token,
            customWidth: 300,
            trans: {
                "key1": "code0"
            },
            elementID: ["usernameID"],
            is_Opt: 0,
            language: "cn",
            isEnabled: true,
            timeout: 3000,
            times: 5,
            apimap: {},
            callback: function (data) {
                if (data.value === "pass") {
                    pointFlag = true;
                }
            }
        };
        nc = new noCaptcha(NC_Opt);
        nc.upLang('cn', {
            _startTEXT: "请按住滑块，拖动到最右边",
            _yesTEXT: "验证通过",
            _error300: "哎呀，出错了，点击<a href=\"javascript:__nc.reset()\">刷新</a>再来一次",
            _errorNetwork: "网络不给力，请<a href=\"javascript:__nc.reset()\">点击刷新</a>",
        });
    }
}
function initCommLogin(){
    $('#LAY-user-login-username').keydown(function(event){
        if(event.keyCode == 13){
            formOn();
        }
    });

    $('#LAY-user-login-password').keydown(function(event){
        if(event.keyCode == 13){
            formOn();
        }
    });

    $("#LAY-user-login-vercode").keydown(function(event){
        if(event.keyCode == 13){
            formOn();
        }
    });
}
function formOn(){
    var currentPanelId= "";
    $("div.loginPanel").each(function(){
        if($(this).css("display")!="none"){
            currentPanelId= $(this).attr("id");
        }
    });
    var loginType= null;
    if(currentPanelId== "forgotPwdPanel"){
        var phone= $('#forgot-phone').val();
        var code= $('#forgot-phoneVercode').val();
        var newPwd= $('#forgot-newPwd').val();
        var repeatNewPwd= $('#forgot-repeatNewPwd').val();
        if(!phone){
            $("#errorMsg").html("请输入手机号");
            return false;
        }
        if(!code){
            $("#errorMsg").html("请输入验证码");
            return false;
        }
        if(!newPwd){
            $("#errorMsg").html("请输入新密码");
            return false;
        }
        var error= systemUserPwdCheck(pwdStrength, newPwd);
        if(error){
            $("#errorMsg").html(error);
            return false;
        }
        if(!repeatNewPwd){
            $("#errorMsg").html("请再次输入新密码");
            return false;
        }
        if(newPwd!=repeatNewPwd){
            $("#errorMsg").html("两次密码输入不一致");
            return false;
        }
        $ajax({
            url: "/manage/updatePwd",
            isShowLayer: false,
            data: {
                phone: phone,
                code: code,
                newPwd:newPwd,
                repeatNewPwd: repeatNewPwd
            },
            succCallback: function (json) {
                if(json.code == 0){
                    layer.msg("修改成功");
                    $("#errorMsg").html("");
                }else{
                    $("#errorMsg").html(json.msg);
                }
            }
        });
        return false;
    }else{
        var userName= "";
        var password= "";
        if(currentPanelId== "userPwdPanel"){
            loginType= "1";
            userName= $('#LAY-user-login-username').val();
            password= $('#LAY-user-login-password').val();
            if(!userName){
                $("#errorMsg").html("请输入用户名");
                return false;
            }
            if(!password){
                $("#errorMsg").html("请输入密码");
                return false;
            }
        }else if(currentPanelId== "phoneCodePanel"){
            loginType= "2";
            userName= $('#login-phone').val();
            password= $('#login-phoneVercode').val();
            if(!userName){
                $("#errorMsg").html("请输入手机号");
                return false;
            }
            if(!/(^$)|^1(3|4|5|7|8)\d{9}$/.test(userName)){
                $("#errorMsg").html("请输入正确的手机号");
                return false;
            }
            if(!password){
                $("#errorMsg").html("请输入验证码");
                return false;
            }
        }
    }

    if(vcCode){
        if(vcCodeType == 1){
            if($('#LAY-user-login-vercode').val() == ""){
                $("#errorMsg").html("请输入图形验证码");
                return false;
            }
        }else if(vcCodeType == 2){
            if (!pointFlag) {
                $("#errorMsg").html("请通过滑块验证");
                return false;
            }
        }else if(vcCodeType == 3){
            if(!captchaFlg){
                $("#errorMsg").html("请通过图形滑块验证");
                return false;
            }
        }
    }
    var b = $('#LAY-user-login-password').val();
    var c = $('#LAY-user-login-username').val();
    var IV= hex_md5(c).substring(0,16);//通过MD5加密用户名获取AES加密密码所需盐值
    var k=encryptedWithIv(b,IV);//加密密码
    var t={
        u:$('#LAY-user-login-username').val(),
        p:k,
        c:$('#LAY-user-login-vercode').val(), //若有验证码加入此句
        cv:$("#captchaVer").val(),
        ly:loginType
    }
    var j=encryptedWithIv(JSON.stringify(t),coin)//通过AES加密登陆请求JSON
    //var j=encryptedWithIv("1234",coin)//通过AES加密登陆请求JSON
    //console.log(j)
    //console.log(decrypte(j))
    $ajax({
        url: "/manage/login",
        isShowLayer: false,
        data: {
            t:j
        },
        //头部传入非关键检验值
        headers:{"dt":new Date().getTime(),"zodiac":"tiger"},
        succCallback: function (json) {
            if(json.code == 0){
                layer.msg("登录成功");
                window.location.href = getContextPath() + "/sys/main/index";
            }else{
                if(vcCode && vcCodeType == 1){
                    changeValidateCode();//修改验证码
                    $('#LAY-user-login-vercode').val('');//验证码
                }
                $("#errorMsg").html(json.msg);
            }
        }
    });
    return false;
}

/**
 *刷新验证码
 */
function changeValidateCode() {
    var obj = $('#verCode');
    var timenow = new Date().getTime();
    var url = getContextPath() + "/manage/kaptcha.jpg?d=" + timenow;
    $(obj).attr("src", url);
}

/**
 * 切换面板，注意：a.dataset.openpanel取值用小写，否则取不到
 * @param a
 * @param linkType 链接类型，1：登录方式切换链接，2：忘记密码切换链接
 */
function changePanel(a, linkType) {
    $("div.loginPanel").hide();
    $("#errorMsg").html("");//清空提示信息
    $("div.loginPanel input").val("");//清空所有值，解决：时尚版切换时若浏览器填入默认用户名密码再切换过去时输入框会全白，不知道为啥
    $("#"+a.dataset.openpanel).show(); //打开新面板

    if(vcCode){//开启验证码
        if(a.dataset.openpanel=='forgotPwdPanel') {//忘记密码
            $(".vercodeBox").hide();//找回密码暂时不要滑块些
        }else{
            $(".vercodeBox").show();
        }
    }
    var loginButtonTip= "登 入";
    if(a.dataset.openpanel=='phoneCodePanel'){//验证码登录
        //切换提示信息
        a.dataset.openpanel= 'userPwdPanel';
        $(a).html("账号密码登录"); //切换提示
        $(a).siblings().hide();//隐藏其他链接
    }else if(a.dataset.openpanel=='forgotPwdPanel'){//忘记密码
        loginButtonTip= "修改密码";
        //切换提示信息
        a.dataset.openpanel= 'userPwdPanel';
        $(a).html("返回登录"); //切换提示
        $(a).siblings().hide();//隐藏其他链接
    }else if(a.dataset.openpanel=='userPwdPanel'){//账号密码登录
        if(linkType== 1){
            //切换提示信息
            a.dataset.openpanel= 'phoneCodePanel';
            $(a).html("验证码登录"); //切换提示
        }else if(linkType== 2){
            //切换提示信息
            a.dataset.openpanel= 'forgotPwdPanel';
            $(a).html("忘记密码？"); //切换提示
        }
        $(a).siblings().show();//显示所有链接
    }
    $("button[lay-filter='LAY-user-login-submit']").html(loginButtonTip);
}

function sendSmsCode(buttonEl, type){
    var phone= $('#login-phone').val();
    if(type=='forgotVercode'){
        phone= $('#forgot-phone').val();
    }
    if(!phone){
        $("#errorMsg").html("请输入手机号");
        return false;
    }
    if(!/(^$)|^1(3|4|5|7|8)\d{9}$/.test(phone)){
        $("#errorMsg").html("请输入正确的手机号");
        return false;
    }
    $ajax({
        url: "/manage/send/verificationCode",
        isShowLayer: false,
        data: {
            phone: phone,
            type: type
        },
        succCallback: function (json) {
            if(json.code == 0){
                layer.msg("验证码发送成功");
                $("#errorMsg").html("");
                var button= $(buttonEl);
                button.attr("disabled","disabled");//禁止点击
                var expireMinuet= parseInt(json.data);//失效分钟数
                button.data("second",expireMinuet*60); //存储为s
                if(expireMinuet==1){
                    button.html(60 +"秒后重新发送");
                }else{
                    button.html(expireMinuet +"分钟后重新发送");
                }
                var timer= setInterval(function(){
                    var second= parseInt(button.data("second"));
                    if(second <= 1){
                        button.removeAttr("disabled");
                        button.html("获取验证码");
                        clearInterval(timer);
                        timer= null;
                    }else{
                        button.data("second",(second-1));
                        button.html(((second-1)>60?(Math.floor((second-1)/60)+"分"):'')+ ((second-1)%60)+"秒后重新发送");
                    };
                },1000);
            }else{
                $("#errorMsg").html(json.msg);
            }
        }
    });
}